<template>
    <el-dialog :title="dialog.type === 'edit' ? '编辑渠道' : dialog.type === 'new' ? '新增渠道' : '渠道信息'"
        :visible.sync="dialog.show"  @close="cancel">
        <el-form v-if="editData" :model="editData" :rules="reductionRules" ref="reductionForm" label-position="left" label-width="120px">
            <el-form-item label="渠道名称" prop="labelName">
                <el-input v-model="editData.labelName" autocomplete="off" :maxlength="15"></el-input>
            </el-form-item>
            <el-form-item label="渠道类型" prop="labelRuleType">
                <el-select  v-model="editData.labelRuleType" filterable :clearable="true" placeholder="请选择类型" @change="handleBlur">
                    <el-option v-for="(item,index) in typeList" :key="index" :label="item.dictLabel"
                        :value="item.dictLabel">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="类型图标" prop="categoryImageUrl">
                <el-upload  class="avatar-uploader" :action="imgUpConfig.addressUrl" :headers="imgUpConfig.headers" :show-file-list="false" accept="image/gif,image/jpeg,image/png,image/jpg,image/bmp" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"> <img v-if="imageUrl||editData.categoryImageUrl" :src="imageUrl||editData.categoryImageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i></el-upload>
            </el-form-item>
            <el-form-item label="类型名称" prop="categoryName">
                <el-input v-model="editData.categoryName" autocomplete="off" :maxlength="15"></el-input>
            </el-form-item>
            <el-form-item label="开始时间" prop="startDate">
                <el-date-picker v-model="editData.startDate" @change="checkDates" value-format="yyyy-MM-dd hh:mm:ss" type="datetime" placeholder="选择开始日期时间"></el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="endDate">
                 <el-date-picker v-model="editData.endDate" @change="checkDates" value-format="yyyy-MM-dd hh:mm:ss" type="datetime" placeholder="选择结束日期时间"></el-date-picker>
            </el-form-item>
            <el-form-item label="选择立减活动" prop="activityIds">
                <el-select multiple v-model="editData.activityIds" filterable :clearable="true" placeholder="请输入立减活动关键词" :loading="reductionLoading">
                    <el-option v-for="item in reductionList" :key="item.activityId" :label="item.activityName"
                        :value="item.activityId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="选择优惠券活动" prop="couponActivityIds" label-width="130px" >
                <el-select multiple v-model="editData.couponActivityIds" filterable :clearable="true" placeholder="请输入优惠券活动关键词" >
                    <el-option v-for="item in couponList" :key="item.id" :label="item.activityName"
                        :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="handleClone">取 消</el-button>
            <el-button v-if="dialog.type === 'edit'" type="primary" @click="handleEditOk">提交</el-button>
            <el-button v-if="dialog.type === 'new'" type="primary" @click="handleAddOk">提交</el-button>
        </div>
    </el-dialog>
</template>
<script>
import {
    listReductionActivity2
} from "@/api/market/reductionActivity";
import {
    addlabel,
    updateLabel,
    getQueryTypeApi
} from "@/api/label/new-label";
import { getLabelCouponActivity } from '@/api/coupon'
import { getToken } from "@/utils/auth";
export default {
    props: {
        parm: {
            type: Object,
            default: null
        }
    },
    data() {
        return {
            dialog: {
                show: this.parm ? this.parm.drawerShow : false,
                type: this.parm ? this.parm.drawerType : 'read', // edit || read || new
            },
            editData: this.parm ? this.parm.editData : {},
            formLabelWidth: '120px',
            reductionList: [], //立减活动数据
            couponList: [], // 优惠券活动数据
            reductionLoading: false,
            reductionRules: {
                labelName: [
                    { required: true, message: '请输入标签名称', trigger: 'blur' },
                ],
                startDate:[
                    { required:true,message:'请选择开始时间',trigger:'blur'}
                ],
                endDate:[
                    {
                        required:true,message:'请选择结束时间',trigger:'blur'
                    }
                ],
                labelRuleType:[
                    {
                      required:true,message:'请选择渠道类型',trigger:'blur'
                    }
                ],
                categoryImageUrl:[
                    {
                       required:true,message:'请上传类型图标',trigger:'blur'
                    }
                ],
                categoryName:[
                    {
                       required:true,message:'请输入类型名称',trigger:'blur'
                    }
                ]
                // activityIds: [
                //     { required: true, message: '请输入立减活动名称', trigger: 'blur' },
                // ],
                // couponActivityIds: [
                //     { required: true, message: '请输入优惠券活动名称', trigger: 'blur' },

                // ]
            },
            imageUrl:'',//类型图标
            imgUpConfig: {
                headers: {
                Authorization: "Bearer " + getToken(),
                },
                addressUrl: process.env.VUE_APP_BASE_API + "/common/upload",
                limit: 6,
            },
            typeList:[]
        }
    },
    created() {
        this.getReduction()
        this.getcouponList()
        this.getQueryType()
    },
    methods: {
        handleBlur() {
            this.$refs.reductionForm.validateField('labelRuleType');
        },
        // 校验时间
        checkDates(){
             // 检查开始时间不得等于结束时间，开始时间不得小于结束时间
             if(this.editData.startDate&&this.editData.endDate){
                const startDate = new Date(this.editData.startDate);
                const endDate = new Date(this.editData.endDate);
                if ((startDate.getTime() === endDate.getTime() )|| (startDate.getTime() > endDate.getTime())) {
                    this.$message.error('开始时间不得等于或小于结束时间');
                    // 如果不符合规定，你可以进行相应的处理，例如重置开始和结束时间
                    // this.editData.startDate = null;
                    // this.editData.endDate=null
                }
             }
        },
        // 审核类型
        async getQueryType(){
            const res=await getQueryTypeApi()
            console.log(res);
            if(res&&res.code==200){
                this.typeList=res.result||[]
                this.$emit('childData',this.typeList);
            }
        },
        // 优惠券活动数据
        getcouponList() {
            getLabelCouponActivity({
              activityStatus: 1
            }).then(res => {
               this.couponList = res.rows
            })
        },
        // 立减活动数据
        getReduction() {
            if (this.loading) return;
            this.reductionLoading = true;
            listReductionActivity2({ activityUse: 'LABEl' }).then(res => {
                if (res && res.code === 200) {
                    this.reductionList = res.rows
                } else {
                    this.reductionList = []
                }
                this.reductionLoading = false;
            })
        },
        authUser(obj) {
            let roles = this.$store.state.user.roles
            let data = obj
            if (!roles.includes('admin')) {
                if (roles.includes('1')) {
                    data.enterpriseId = this.presentEnterprise.enterpriseId
                } else {
                    data.enterpriseId = this.presentEnterprise.enterpriseId
                    data.stationId = this.presentSation
                }
            }
            return data
        },
        cancel() {
            this.$nextTick(() => {
                this.$refs['reductionForm'].clearValidate();
                this.imageUrl=''
            })
        },
        handleClone() {
            this.dialog.show = false
        },
        handleAddOk() {
            if (!this.presentEnterprise) {
                return this.$message.error('请登录油企账号');
            }
            this.$refs['reductionForm'].validate((valid) => {
                if (valid) {
                    this.$refs.reductionForm.clearValidate('categoryImageUrl');
                    let labelRule = this.editData
                    labelRule.enterpriseId = this.presentEnterprise.enterpriseId
                    if(labelRule.couponActivityIds){
                        labelRule.couponActivityIds = this.editData.couponActivityIds.join(",")
                    }
                    if(labelRule.activityIds){
                        labelRule.activityIds = this.editData.activityIds.join(",")
                    }
                    labelRule.delFlag = '0'
                    if(labelRule.startDate&&labelRule.endDate){
                        const startDate = new Date(labelRule.startDate);
                        const endDate = new Date(labelRule.endDate);
                        if ((startDate.getTime() === endDate.getTime() )|| (startDate.getTime() > endDate.getTime())) {
                            this.$message.error('开始时间不得等于或小于结束时间');
                            // 如果不符合规定，你可以进行相应的处理，例如重置开始和结束时间
                            // this.editData.startDate = null;
                            // this.editData.endDate=null
                        }else{ 
                            addlabel(labelRule).then(res => {
                                if (res && res.code === 200) {
                                    this.$message.success('新增成功');
                                    this.$emit('on-submit-new')
                                    this.dialog.show = false
                                } else {
                                    this.$message.error(res.msg);
                                }
                            })
                        }
                    }
                    
                }
            });
        },
        handleEditOk() {
            this.$refs['reductionForm'].validate((valid) => {
                if (valid) {
                    this.$refs.reductionForm.clearValidate('categoryImageUrl');
                    let labelRule = this.editData
                    if(labelRule.couponActivityIds) {
                        labelRule.couponActivityIds = this.editData.couponActivityIds.join(",")
                    }
                    if(labelRule.activityIds) {
                        labelRule.activityIds = this.editData.activityIds.join(",")
                    }
                     if(labelRule.startDate&&labelRule.endDate){ 
                        const startDate = new Date(labelRule.startDate);
                        const endDate = new Date(labelRule.endDate);
                         if ((startDate.getTime() === endDate.getTime() )|| (startDate.getTime() > endDate.getTime())) {
                            this.$message.error('开始时间不得等于或小于结束时间');
                            // 如果不符合规定，你可以进行相应的处理，例如重置开始和结束时间
                            // this.editData.startDate = null;
                            // this.editData.endDate=null
                        }else{ 
                            updateLabel(labelRule).then(res => {
                        if (res && res.code === 200) {
                            this.$message.success('修改成功');
                            this.$emit('on-submit-edit')
                            this.dialog.show = false
                        } else {
                            this.$message.error(res.msg);
                        }
                    })
                        }
                     }
                    
                }
            });
        },
        // 校验上传文件大小
        beforeAvatarUpload(file) {
            // 检查图片大小是否小于 5MB
            const isLt5M = file.size / 1024 / 1024 < 5;
            console.log(file);
            // 如果图片大小超过 5MB，显示错误信息
            if (!isLt5M) {
                this.$message.error('上传图片大小不能超过5MB！');
            }else if (file.type== 'image/tiff'||file.type == 'image/tif') {
                this.$message.error('上传图片必须是除TIFF以外的其他格式！');
            }

            // 返回是否满足上传条件（大小不超过5MB）
            return isLt5M
        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = res.url;
            this.editData.categoryImageUrl = res.url;
            this.$refs.reductionForm.clearValidate('categoryImageUrl');
        },

    },
    watch: {
        parm(newValue) {
            this.dialog.show = newValue.drawerShow;
            this.dialog.type = newValue.drawerType;
            this.editData = newValue.editData
        }
    }
}
</script>
<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
